package com.up4years.controller.base;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJacksonJsonView;

import com.up4years.dataapi.entity.base.Page;
import com.up4years.utils.CommonUtil;

@Controller
public class BaseController {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	public static final String SUCCESS = "success";
	public static final String FAIL = "fail";
	public static final String ERROR = "error";
	protected static final int RESCODE_OK = 200;
	protected static final int RESCODE_FAIL = 201;
	protected static final int SYSTEM_ERROR = 100;
 
    @ExceptionHandler(Exception.class)
	public ModelAndView handleException(Exception ex, HttpServletRequest request) {
		ex.printStackTrace();
		logger.info(this.getRequestMap(request) + ex.getMessage());
		// todo:需要在下一版本中梳理各个流程中的异常分支，统一系统异常和业务异常code
		if (ex instanceof SaleException) {
			SaleException se = (SaleException) ex;
			return new ModelAndView(new MappingJacksonJsonView(),
					getFailResult(se.getMessage(),
							Integer.parseInt(se.getErrorCode())));
		}
		// String msg = (ex instanceof SaleException) ? ex.getMessage() :
		// "系统错误";
		// 如果是ajax请求返回json结果，普通的就返回至error.jsp
		// return isAjax(request) ? new ModelAndView(new
		// MappingJacksonJsonView(), getFailResult(msg))
		// : new ModelAndView("error", "msg", msg);
		return new ModelAndView(new MappingJacksonJsonView(), getFailResult(
				"系统错误", SYSTEM_ERROR));
	}

	protected Map<String, Object> getFailResult(String msg, int code) {
		return getResult(false, code, msg, Collections.EMPTY_MAP);
	}

	protected Map<String, Object> getFailResult(String msg) {
		return getResult(false, RESCODE_FAIL, msg, Collections.EMPTY_MAP);
	}

	protected Map<String, Object> getResult(boolean isOk, int resCode,
			String errorMsg, Object obj) {
		return createJson(isOk, resCode, errorMsg, obj);
	}

	protected Map<String, Object> createJson(boolean isOk, int resCode,
			String errorMsg, Object obj) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		jsonMap.put("result", isOk ? "ok" : "fail");
		jsonMap.put("rescode", resCode);
		jsonMap.put("msg", errorMsg);
		jsonMap.put("data", obj);
		return jsonMap;
	}

	protected boolean isAjax(HttpServletRequest request) {
		return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
	}

	protected Map<String, Object> getSuccessResult() {
		return getResult(true, RESCODE_OK, "操作成功！", Collections.EMPTY_MAP);
	}

	protected Map<String, Object> getSuccessResult(Object obj) {
		return getResult(true, RESCODE_OK, "操作成功", obj);
	}

	public Map<String, String> getRequestMap(HttpServletRequest request) {
		Map<String, String> resultMap = new HashMap<String, String>();
		Map<?, ?> requestMap = request.getParameterMap();
		for (Object key : requestMap.keySet()) {
			resultMap.put(String.valueOf(key),
					request.getParameter(String.valueOf(key)) == null ? ""
							: request.getParameter(String.valueOf(key)).trim());
		}
		return resultMap;
	}
	public <T> Page<T> getPage(HttpServletRequest request){
		int pageNo = StringUtils.isBlank(request.getParameter("pageNo")) ? 1 : Integer.valueOf(request.getParameter("pageNo"));
		int pageSize = StringUtils.isBlank(request.getParameter("pageSize")) ?  CommonUtil.getDefaultPageSize():Integer.valueOf(request.getParameter("pageSize"));
		return new Page<T>(pageNo,pageSize);
	}
}
